package com.utils.redis.utils;

import com.utils.redis.PropertiesUtils;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author xin.ding
 * @date 2020/9/19 11:26
 */
public class JedisClientPool {
    public static JedisClientPool jedisClientPool = getInstance();
    public static JedisPool jedisPool;
    public static int maxTotal;
    public static int maxIdle;
    public static int maxWaitMillis;

    public static synchronized JedisClientPool getInstance() {
        if (null == jedisClientPool) {
            jedisClientPool = new JedisClientPool();
        }
        return jedisClientPool;
    }

    public JedisClientPool() {
        if (null == jedisPool) {
            init();
        }
    }

    /**
     * 初始化Jedis
     *
     * @return
     */
    private static JedisPoolConfig initPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大分配的对象数
        jedisPoolConfig.setMaxTotal(maxTotal);
        // jedis实例
        jedisPoolConfig.setMaxIdle(maxIdle);
        // 最大等待时间
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        jedisPoolConfig.setTestOnBorrow(true);
        // 是否进行有效性检查
        jedisPoolConfig.setTestOnReturn(true);
        return jedisPoolConfig;
    }

    /**
     * 初始化jedis连接池
     */
    public static void init() {
        maxTotal = Integer.parseInt(PropertiesUtils.getValue("redis.pool.maxTotal"));
        maxIdle = Integer.parseInt(PropertiesUtils.getValue("redis.pool.maxIdle"));
        maxWaitMillis = Integer.parseInt(PropertiesUtils.getValue("redis.pool.maxWaitMillis"));
        JedisPoolConfig jedisPoolConfig = initPoolConfig();
        String host = PropertiesUtils.getValue("redis.host");
        int port = Integer.parseInt(PropertiesUtils.getValue("redis.port"));
        // 构造连接池
        jedisPool = new JedisPool(jedisPoolConfig, host, port);
    }
}
